package cn.HuanG.org.controller;

import cn.HuanG.org.domain.Department;
import cn.HuanG.org.query.DepartmentQuery;
import cn.HuanG.org.service.IDepartmentService;
import cn.HuanG.util.AjaxResult;
import cn.HuanG.util.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * controller模块
 */
@RestController
@RequestMapping("/department")
public class DepartmentController {
    @Autowired
    private IDepartmentService departmentService;

    @GetMapping
    public List<Department> getAll(){
        return  departmentService.queryAll();
    }

    @PutMapping
    public AjaxResult saveOrUpdate(@RequestBody Department department){
        try {
            if(department.getId()==null){
                departmentService.save(department);
            }else {
                departmentService.update(department);
            }
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage(e.getMessage());
        }
    }
    @GetMapping("/{id}") //查询，区分通过uri（id占位符）
    public Department findById(@PathVariable("id") Long id){
       return departmentService.queryById(id);
    }

    @PostMapping  //分页专用
    public PageInfo<Department> page(@RequestBody DepartmentQuery query){
       return departmentService.queryPage(query);

    }
    @DeleteMapping("/{id}")
    public AjaxResult delete(@PathVariable("id") Long id){
        try {
            departmentService.delete(id);
            return AjaxResult.me();
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.me().setMessage(e.getMessage());
        }
    }
    @PatchMapping
    public AjaxResult batchDelete(@RequestBody Long[] ids){
        try {
            System.out.println(ids);
            departmentService.batchDel(ids);
            return AjaxResult.me();
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.me().setMessage(e.getMessage());
        }
    }

    /*获取部门树的方法*/
    @GetMapping("/deptTree")
    public List<Department> getDeptTree(){
        return departmentService.getDeptTree();
    }
}

























